package swa.group22;
import java.util.Collection;

import swa2012.telco.broker.beans.Client;
import swa2012.telco.broker.beans.Message;

import javax.jws.WebService;

@WebService(endpointInterface = "swa.group22.iProviderService")

/**
 * 
 * @author Simon
 *
 */
public class ProviderService implements iProviderService {
	
	private ClientStore clientStore;
	private MessageStore messageStore;
	private ProviderApplication providerApplication;

	/**
	 * 
	 */
	public ProviderService() {
		
	}
	
	public ProviderService(ClientStore clientStore, MessageStore messageStore,
			ProviderApplication providerApplication) {
		super();
		this.clientStore = clientStore;
		this.messageStore = messageStore;
		this.providerApplication = providerApplication;
	}

	/**
	 * Method for clients to register at the provider.
	 * 
	 * @param id id of the client
	 * @return client bean
	 */
	@Override
	public Client register(String id) {
		Client client = new Client(id, providerApplication.getProvider());
		clientStore.addClient(client);
		
		return client;
	}

	/**
	 * Method for clients to deregister at the provider.
	 * 
	 * @param id id of the client
	 */
	@Override
	public void deregister(String id) {
		clientStore.removeClient(id);
	}

	/**
	 * Method to get the messages from the provider.
	 * 
	 * @param id id of the client
	 * @return message bean
	 */
	@Override
	public Collection<Message> getMessages(String id) {
		Collection<Message> messages = messageStore.getMessages(id);
		return messages;
	}

	/**
	 * Method to send a message to another client.
	 * 
	 * @param message message to send
	 */
	@Override
	public void sendMessage(Message message) {
		message.setTimestamp(Long.valueOf(System.currentTimeMillis()));
		
		if ((message.getSender() == null) || (message.getReceiver() == null) || (message.getText() == null) || (message.getTimestamp() == null)) {
			if ((message.getSender().getID() == null) || (message.getSender().getProvider() == null) || (message.getReceiver().getID() == null) || (message.getReceiver().getProvider() == null)) {
				return;
			} else {
				if (message.getReceiver().getProvider().getID().equals(this.providerApplication.getProvider().getID())) {
					this.messageStore.addMessage(message);
				} else {
					this.providerApplication.getBroker().sendMessage(message);
				}
			}
		}
	}

	/**
	 * Method to list all connected clients.
	 * 
	 * @return collection of client beans
	 */
	@Override
	public Collection<Client> listClients() {
		return this.providerApplication.getBroker().listClients();
	}

}
